AI
The useAI hook from the Blotch Library sends a prompt to an AI model and gives you its reply. Use it for content that is different every time, such as a daily poem, a fun fact or a summary of data your Widget already has.
import { useAI } from "~lib/use-ai";
const Widget = () => {
const { data } = useAI({ prompt: "Write a haiku about autumn" });
return <p className="whitespace-pre-line">{data.output}</p>;
};
Like useFetch, your Widget waits for the reply before it is drawn, so data is always there. No API key is needed.
Building the prompt from data
The prompt is an ordinary string, so you can fill it with Inputs or with data you have already fetched:
import { useAI } from "~lib/use-ai";
import { useFetch } from "~lib/use-fetch";
type Forecast = {
readonly temperature: number;
readonly summary: string;
};
const Widget = () => {
const { data: forecast } = useFetch<Forecast>(
"https://api.example.com/forecast",
);
const { data } = useAI({
prompt: `In one short sentence, suggest what to wear today. It will be ${forecast.temperature}°C and ${forecast.summary}.`,
});
return <p>{data.output}</p>;
};
Tips
- Ask for the shape you want. The reply is plain text. Say how long it should be and how it should be laid out, such as "one sentence" or "three bullet points", so it fits your
Widget. - Expect a new reply every time. Each time the Frame is prepared, the prompt is sent again and the model writes a fresh reply.
warning
Use one useAI per Widget. A second useAI gets the first one's reply, so ask for everything you need in one prompt.
Reference
import { useAI } from "~lib/use-ai";
const { data } = useAI({ prompt });
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
prompt | string | Yes | The text to send to the model. |
Returns
| Property | Type | Description |
|---|---|---|
data.output | string | The model's reply. |